package com.example.wyh.intelcheckbash.task;

import com.example.wyh.intelcheckbash.LoginActivity;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;

import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.common.SysExitUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by chen on 17/10/20.
 */

public class DownloadTaskActivity extends AppCompatActivity {
    ProgressBar mProgressBar;
    CalendarView mCalendarView;
    String mSelectDate;
    TextView mSelectTextView;
    Button mDownloadTaskBtn;
    String mDeviceToken;
    String mYhxtm;
    String mSelectBC;
    Thread mDownLoadThread = null;
    RelativeLayout mShow_bc_layout;
    boolean isDownloadComplete;
    RelativeLayout selectCalendarRL;
    RelativeLayout download_progress_RL;

//    public JSONObject handleUserTaskList(String type, JSONObject newTask) {
//        JSONArray newTaskList = new JSONArray();
//        String localStorageKey = "recodeDownLoadTask_" + LocalStorage.getUserXtm(DownloadTaskActivity.this);
//        JSONObject recodeDownLoadTask = LocalStorage.getObject(DownloadTaskActivity.this, localStorageKey);
//        JSONObject selectDateTask = new JSONObject();
//        try {
//            selectDateTask = recodeDownLoadTask.getJSONObject(mSelectDate);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            selectDateTask.put(type, newTask);
//            recodeDownLoadTask.put(mSelectDate, selectDateTask);
//            LocalStorage.saveObject(DownloadTaskActivity.this, localStorageKey, recodeDownLoadTask);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        JSONArray types = getTypeList();
//        for (int j = 0; j < types.length(); j++) {
//            try {
//                JSONArray data = selectDateTask.getJSONObject(types.getString(j)).getJSONArray("data");
//                for (int i = 0; i < data.length(); i++) {
//                    newTaskList.put(data.getJSONObject(i));
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//
//
//        JSONObject currentTaskList = new JSONObject();
//        try {
//            currentTaskList.put("data", newTaskList);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return currentTaskList;
//
//
//    }

//    public JSONArray getTypeList() {
//        JSONArray types = new JSONArray();
//        types.put("后夜班").put("白班").put("前夜班").put("燃料夜班").put("燃料白班");
//        return types;
//    }

    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(DownloadTaskActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("任务下载");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.download_title);

        RelativeLayout bar_back_btn = (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadTaskActivity.this.finish();
            }
        });


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_task);
        SysExitUtil.activityList.add(DownloadTaskActivity.this);
        initActionBar();
        mSelectBC = "白班";
        mShow_bc_layout = (RelativeLayout) findViewById(R.id.show_bc_layout);

        initDownloadTaskBtnAndProgressBar();
        initSelectBCSpinner();

        mDeviceToken = getIntent().getStringExtra("deviceToken");
        mYhxtm = getIntent().getStringExtra("yhxtm");
        Date day = new Date();
        mSelectDate = HttpUtil.getCurrentDateString();

        initDateShowTextView(mSelectDate);

        selectCalendarRL = (RelativeLayout) findViewById(R.id.selectCalendarRL);
        selectCalendarRL.setVisibility(View.GONE);
        mCalendarView = (CalendarView) findViewById(R.id.selectCalendarView);
        mCalendarView.setVisibility(View.GONE);
        download_progress_RL = (RelativeLayout)findViewById(R.id.download_progress_RL);
        download_progress_RL.setVisibility(View.VISIBLE);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
                String month = i1 + 1 < 10 ? "0" + (i1 + 1) : (i1 + 1) + "";
                String day = i2 < 10 ? "0" + i2 : i2 + "";
                mSelectDate = i + "-" + month + "-" + day;
                mSelectTextView.setText(mSelectDate);
                mDownloadTaskBtn.setText("下载任务");
                mCalendarView.setVisibility(View.GONE);
                selectCalendarRL.setVisibility(View.GONE);
                mShow_bc_layout.setVisibility(View.VISIBLE);
                sendMsg(0, 100);
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            stopDownLoadThread();
            DownloadTaskActivity.this.finish();


        }
        return true;
//        return super.onKeyDown(keyCode, event);
    }

    public void initSelectBCSpinner() {
        Spinner spinner = (Spinner) findViewById(R.id.select_bc);
        spinner.setPrompt("选择需要下载任务的班次");
        final ArrayList<String> list = new ArrayList<String>();
        list.add("白班");
        list.add("前夜班");
        list.add("后夜班");
        list.add("燃料夜班");
        list.add("燃料白班");
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSelectBC = list.get(position);
                mDownloadTaskBtn.setText("下载任务");
                sendMsg(0, 100);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    public void initDownloadTaskBtnAndProgressBar() {
        mDownloadTaskBtn = (Button) findViewById(R.id.download_task_btn);
        mDownloadTaskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDownloadTaskBtn.getText().equals("下载任务")) {
                    mDownloadTaskBtn.setText("重新下载任务");
                }
                stopDownLoadThread();
                mDownLoadThread = HttpUtil.requestNetForGetDownloadTask(DownloadTaskActivity.this, mYhxtm, mSelectDate, mSelectBC, mDeviceToken);
                mDownLoadThread.start();
                mSelectTextView.setText(mSelectDate);
            }
        });
        mProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);
    }

    public void stopDownLoadThread() {
        if (mDownLoadThread != null && mDownLoadThread.isAlive()) {
            //Log.e("readCacheThread", "thread interrupt_1");
            mDownLoadThread.interrupt();
            //Log.e("status", ""+readCacheThread.isInterrupted());
        }
    }

    public void initDateShowTextView(String date) {
        mSelectTextView = (TextView) findViewById(R.id.select_date);
        mSelectTextView.setText(date);
        mSelectTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCalendarView.getVisibility() == View.VISIBLE) {
                    mCalendarView.setVisibility(View.GONE);
                    mShow_bc_layout.setVisibility(View.VISIBLE);
                    selectCalendarRL.setVisibility(View.GONE);
                } else {
                    mCalendarView.setVisibility(View.VISIBLE);
                    selectCalendarRL.setVisibility(View.VISIBLE);
                    mShow_bc_layout.setVisibility(View.INVISIBLE);
                }
            }
        });
    }


    public void saveAllData(Message msg) {
        switch (msg.what) {
            case 0:
                try {
                    JSONObject msgData = new JSONObject(msg.obj.toString());
                    JSONArray taskData = msgData.getJSONArray("data");
                    testTaskSave(taskData);
                    Log.e("==========end", new Date().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendMsgOk();
        }

    }

    public void sendMsg(int revice, int all) {

        double a = (revice * 100.0 / all);
        int num = (int) Math.floor(a);
        if (num >= 100) {
            num = 99;
        }
        mProgressBar.setProgress(num);

    }

    public void sendMsgOk() {
        mProgressBar.setProgress(100);
        Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(DownloadTaskActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void sendNetWorkError()
    {
        Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                LayoutInflater layoutInflater = LayoutInflater.from(DownloadTaskActivity.this);
                final View layout = layoutInflater.inflate(R.layout.promot_alert,
                        null);

                final AlertDialog alertDialog = new AlertDialog.Builder(DownloadTaskActivity.this).setTitle("").setView(layout)
                        .setPositiveButton("",  new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .setNegativeButton("", null).show();

                TextView alert_title = (TextView)layout.findViewById(R.id.promot_alert_title);
                alert_title.setText("请检查网络是否连接好");
                Button confirm = (Button)layout.findViewById(R.id.promot_confirm);
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
//                Toast.makeText(DownloadTaskActivity.this, "请检查网络是否连接好", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void testTaskSave(JSONArray taskDate) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(DownloadTaskActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        db.beginTransaction();
        String query = "time = '" + mSelectTextView.getText().toString() +
                    "' and user_id = '" + LocalStorage.getUserXtm(DownloadTaskActivity.this)
                    + "'" + " and bc='" + mSelectBC +"'";
        db.delete("task", query, null);

        try {
            for (int i = 0; i < taskDate.length(); i++) {
                ContentValues cv = new ContentValues();
                try {
                    cv.put("task_id", taskDate.getJSONObject(i).getString("xtm"));
                    cv.put("bc", mSelectBC);
                    cv.put("user_id", LocalStorage.getUserXtm(DownloadTaskActivity.this));
                    cv.put("data", taskDate.getJSONObject(i).toString());
                    cv.put("is_complete", false);
                    cv.put("start_date",taskDate.getJSONObject(i).getString("validstarttime").substring(0,10));
                    cv.put("end_date",taskDate.getJSONObject(i).getString("validendtime").substring(0,10));
                    cv.put("time", mSelectDate);
                    db.insert("task", null, cv);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        db.close();
    }

}


